package cn.m1c.cntt.wuhan2020.cnttlifegoods.common.utils

import cn.m1c.cntt.wuhan2020.cnttlifegoods.common.model.ResultVo
import cn.m1c.cntt.wuhan2020.cnttlifegoods.person.vo.UserVo
import com.alibaba.fastjson.JSON
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.HttpClientBuilder
import org.apache.http.util.EntityUtils
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

//详情request
fun <T> out(response: HttpServletResponse, data : ResultVo<T>){
    val out = response.writer
    out.print(JSON.toJSONString(data))
    out.flush()
}
val AUTHED_USER_KEY = "__AUTHED_USER__"
fun setAuthUser(request: HttpServletRequest, userVo: UserVo){
    request.setAttribute(AUTHED_USER_KEY,userVo)
}
fun getAuthUser(request: HttpServletRequest):UserVo{
    return request.getAttribute(AUTHED_USER_KEY) as UserVo
}

//暂时无用
fun setResponseHeaders(response: HttpServletResponse){
    response.setCharacterEncoding("utf-8")
    if (response.getContentType()!=null && response.getContentType().length>0){
        response.setContentType("application/json")
    }
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate")
    response.setHeader("Pragma", "no-cache")
    response.setDateHeader("Expires", 3600L)
    response.setHeader("connection", "close")
    response.setHeader("Access-Control-Max-Age", "3600")
    response.setHeader("Access-Control-Allow-Origin", "*")
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE")
    response.addHeader("Access-Control-Allow-Headers", "access-control-allow-origin, x-requested-with, content-type, Accept, x-xsrf-token, Authorization,token")
    response.setStatus(200)
}

fun get(url:String):String{
    val client = HttpClientBuilder.create().build()
    val get = HttpGet(url)
    val res = client.execute(get!!)
    val entity = res.entity
    var responseContent = EntityUtils.toString(entity, "UTF-8")
    return responseContent
}
